package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import dao.StoDao;
import entity.Sto;
import util.DBUtils;

public class StoDaoImpl implements StoDao {

	@Override
	public boolean insert(Sto sto) {
		try(Connection c = DBUtils.getConnection();){
			String sql="insert into sto values(?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement ps = c.prepareStatement(sql);
			// 设置参数
			ps.setString(1,sto.getStoid());
			ps.setString(2,sto.getStoticket());
			ps.setString(3,sto.getPaykind());
			ps.setTimestamp(4,sto.getStotime());
			ps.setInt(5,sto.getStocount());
			ps.setDouble(6,sto.getStoprice());
			ps.setString(7,sto.getStoperson());
			ps.setDouble(8,sto.getTotalprice());
			ps.setString(9,sto.getChkperson());
			ps.setString(10,sto.getChkval());
			ps.setString(11, sto.getWareid());
			// 执行
			return ps.executeUpdate() == 1 ? true: false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean updatePersonAndChkVal(String stoticket, String chkperson, String chkval) {
		try(Connection c = DBUtils.getConnection();){
			String sql="update sto set chkperson=?,chkval=? where stoticket=? and stoperson!=?";
			PreparedStatement ps = c.prepareStatement(sql);
			// 设置参数
			ps.setString(1,chkperson);
			ps.setString(2,chkval);
			ps.setString(3,stoticket);
			ps.setString(4,chkperson);
			
			// 执行
			return ps.executeUpdate() == 1 ? true: false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public List<Sto> selectByWareId(String wareid) {
		try(Connection c = DBUtils.getConnection();){
			String sql = "select stoid,stoticket,paykind,stotime,stocount,stoprice,stoperson,"
					+ " totalprice,chkperson,chkval,wareid from sto where wareid=?";
			PreparedStatement ps = c.prepareStatement(sql);
			ps.setString(1, wareid);
			// 执行查询
			ResultSet rs = ps.executeQuery();
			List<Sto> stos = new ArrayList<>();
			// 遍历
			while (rs.next()) {
				Sto sto = new Sto();
				sto.setStoid(rs.getString(1));
				sto.setStoticket(rs.getString(2));
				sto.setPaykind(rs.getString(3));
				sto.setStotime(rs.getTimestamp(4));
				sto.setStocount(rs.getInt(5));
				sto.setStoprice(rs.getDouble(6));
				sto.setStoperson(rs.getString(7));
				sto.setTotalprice(rs.getDouble(8));
				sto.setChkperson(rs.getString(9));
				sto.setChkval(rs.getString(10));
				sto.setWareid(rs.getString(11));
				// 添加到集合
				stos.add(sto);
			}
			return stos.isEmpty() ? Collections.emptyList() : stos;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}

}










